package com.lihui.demo;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 功能描述
 *
 * @author wileda
 * @date 2022/12/28  13:57
 */
public class SelectAllDemo {
    public static void main(String[] args) {

        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setURL("jdbc:mysql://localhost:3306/java_database?characterEncoding=UTF-8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("123456");

        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;

        try {
            //连接数据库
            connection = dataSource.getConnection();
            //构造sql语句
            String sql =  "select id, sn, name, qq_mail, classes_id from student";
            //获取sql处理对象
            statement = connection.prepareStatement(sql);
            //执行sql
            resultSet = statement.executeQuery();
            while(resultSet.next()){
                int id = resultSet.getInt("id");
                String sn = resultSet.getString("sn");
                //姓名
                String name = resultSet.getString("name");
                //邮箱
                String mail = resultSet.getString("qq_mail");
                //班级编号
                int classesId = resultSet.getInt("classes_id");
                //结果
                System.out.println("Id = " + id + ", 学号 = " + sn + ", 姓名 = " + name + ", 邮箱 = " + mail + ", 班级编号 = " + classesId);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            if(resultSet != null){
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(statement != null){
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(connection != null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
